<template>
  <div class="iframe-container">
    <iframe id="iframeContainer" :src="iframeUrl" frameborder="0" @load="onIframeLoad"/>
  </div>
</template>
<script>

export default {
  name: 'IframeContainer',
  props: {
    iframeUrl: {
      type: String,
      default: ''
    },
  },
  data() {
    return {}
  },
  mounted() {
    const that = this

    this.$nextTick(() => {
      this.initIframe()
      window.addEventListener('resize', that.initIframe);
    })

    window.addEventListener('message', function (event) {
      // 获取传递的数据
      const data = event.data;
      that.$emit('iframe_receive_data', data)
    });
  },
  methods: {
    initIframe() {
      const iframeContainer = document.getElementById('iframeContainer')
      const width = (Number(document.body.clientWidth) - 40)
      const height = (Number(document.body.clientHeight) - 180)
      const scaleX = width / 1880
      const scaleY = height / 900
      iframeContainer.style.transform = `scale(${scaleX}, ${scaleY})`
    },
    onIframeLoad(){
      return this.$emit('iframe_loaded')
    },
    triggerIframeEvent(data) {
      const iframe = document.getElementById('iframeContainer');
      iframe.contentWindow.postMessage(data, '*'); // '*' 表示允许任何源，生产环境中应指定具体的源
      // console.log('triggerIframeEvent done', data)
    }
  },
}
</script>
<style lang="scss" scoped>
.iframe-container {
  width: 100%;
  height: 100%;

  iframe {
    width: 1880px;
    height: 900px;
    top: 0;
    left: 0;
    transform-origin: top left;
  }
}
</style>
